<!DOCTYPE html>
<html>
<head>
    <title>登录注册系统</title>
    <style>
        body { margin:0; padding:0; height:100vh; display:flex; justify-content:center; align-items:center; background:#f5f5f5; }
        .container { width:300px; padding:20px; background:white; border-radius:5px; box-shadow:0 0 10px rgba(0,0,0,0.1); }
        input { width:100%; padding:10px; margin:8px 0; border:1px solid #ddd; border-radius:3px; }
        button { width:100%; padding:10px; background:#4285f4; color:white; border:none; border-radius:3px; cursor:pointer; }
        .hidden { display:none; }
        .error { color:red; margin-top:10px; }
    </style>
</head>
<body>
    <div class="container">
        <!-- 登录表单 -->
        <div id="login-form">
            <h2>登录</h2>
            <input id="login-username" placeholder="用户名" required>
            <input id="login-password" type="password" placeholder="密码" required>
            <button id="login-btn">登录</button>
            <p>没有账号？<a href="#" onclick="showRegister()">注册</a></p>
            <div id="login-error" class="error"></div>
        </div>
        
        <!-- 注册表单 -->
        <div id="register-form" class="hidden">
            <h2>注册</h2>
            <input id="reg-username" placeholder="用户名" required>
            <input id="reg-password" type="password" placeholder="密码" required>
            <button id="register-btn">注册</button>
            <p>已有账号？<a href="#" onclick="showLogin()">登录</a></p>
            <div id="reg-error" class="error"></div>
        </div>
    </div>

    <script>
        // ========== 前端代码 ==========
        // 显示注册表单
        function showRegister() {
            document.getElementById('login-form').classList.add('hidden');
            document.getElementById('register-form').classList.remove('hidden');
            clearErrors();
        }
        
        // 显示登录表单
        function showLogin() {
            document.getElementById('register-form').classList.add('hidden');
            document.getElementById('login-form').classList.remove('hidden');
            clearErrors();
        }
        
        // 清除错误信息
        function clearErrors() {
            document.getElementById('login-error').textContent = '';
            document.getElementById('reg-error').textContent = '';
        }
        
        // 注册功能
        document.getElementById('register-btn').addEventListener('click', async function() {
            const username = document.getElementById('reg-username').value;
            const password = document.getElementById('reg-password').value;
            
            if(!username || !password) {
                document.getElementById('reg-error').textContent = '请填写用户名和密码';
                return;
            }
            
            try {
                const response = await fetch('/register', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, password })
                });
                
                const data = await response.json();
                
                if(data.success) {
                    alert('注册成功！');
                    showLogin();
                    document.getElementById('login-username').value = username;
                } else {
                    document.getElementById('reg-error').textContent = data.message || '注册失败';
                }
            } catch (error) {
                document.getElementById('reg-error').textContent = '网络错误，请重试';
                console.error('注册错误:', error);
            }
        });
        
        // 登录功能
        document.getElementById('login-btn').addEventListener('click', async function() {
            const username = document.getElementById('login-username').value;
            const password = document.getElementById('login-password').value;
            
            if(!username || !password) {
                document.getElementById('login-error').textContent = '请输入用户名和密码';
                return;
            }
            
            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, password })
                });
                
                const data = await response.json();
                
                if(data.success) {
                    // 登录成功，跳转到用户页面并传递UID和用户名
                    window.location.href = `user.html?uid=${data.uid}&username=${encodeURIComponent(username)}`;
                } else {
                    document.getElementById('login-error').textContent = data.message || '登录失败';
                }
            } catch (error) {
                document.getElementById('login-error').textContent = '网络错误，请重试';
                console.error('登录错误:', error);
            }
        });

        // ========== 后端代码 ==========
        // 使用Node.js原生HTTP模块创建服务器
        if (typeof require !== 'undefined') {
            const http = require('http');
            const url = require('url');
            const fs = require('fs');
            const path = require('path');
            
            // 用户数据存储
            let users = {};
            let uidCounter = 1;
            const USER_FILE = path.join(__dirname, 'users.json');
            
            // 加载用户数据
            function loadUsers() {
                try {
                    if (fs.existsSync(USER_FILE)) {
                        const data = fs.readFileSync(USER_FILE, 'utf8');
                        users = JSON.parse(data);
                        // 设置UID计数器
                        const maxUid = Math.max(...Object.values(users).map(u => u.uid), 0);
                        uidCounter = maxUid + 1;
                    }
                } catch (error) {
                    console.error('加载用户数据失败:', error);
                }
            }
            
            // 保存用户数据
            function saveUsers() {
                try {
                    fs.writeFileSync(USER_FILE, JSON.stringify(users, null, 2));
                    return true;
                } catch (error) {
                    console.error('保存用户数据失败:', error);
                    return false;
                }
            }
            
            // 启动时加载用户数据
            loadUsers();
            
            // 创建HTTP服务器
            const server = http.createServer(async (req, res) => {
                const parsedUrl = url.parse(req.url, true);
                
                // 静态文件服务
                if (req.method === 'GET' && parsedUrl.pathname === '/') {
                    res.writeHead(200, { 'Content-Type': 'text/html' });
                    res.end(fs.readFileSync(path.join(__dirname, 'index.html')));
                    return;
                }
                
                // 注册接口
                if (req.method === 'POST' && parsedUrl.pathname === '/register') {
                    let body = '';
                    req.on('data', chunk => body += chunk.toString());
                    req.on('end', () => {
                        try {
                            const { username, password } = JSON.parse(body);
                            
                            if (users[username]) {
                                res.writeHead(400, { 'Content-Type': 'application/json' });
                                res.end(JSON.stringify({ success: false, message: '用户名已存在' }));
                                return;
                            }
                            
                            const uid = uidCounter++;
                            users[username] = { uid, password };
                            
                            if (saveUsers()) {
                                res.writeHead(200, { 'Content-Type': 'application/json' });
                                res.end(JSON.stringify({ success: true, uid }));
                            } else {
                                res.writeHead(500, { 'Content-Type': 'application/json' });
                                res.end(JSON.stringify({ success: false, message: '注册失败，请重试' }));
                            }
                        } catch (error) {
                            res.writeHead(400, { 'Content-Type': 'application/json' });
                            res.end(JSON.stringify({ success: false, message: '无效请求' }));
                        }
                    });
                    return;
                }
                
                // 登录接口
                if (req.method === 'POST' && parsedUrl.pathname === '/login') {
                    let body = '';
                    req.on('data', chunk => body += chunk.toString());
                    req.on('end', () => {
                        try {
                            const { username, password } = JSON.parse(body);
                            const user = users[username];
                            
                            if (!user || user.password !== password) {
                                res.writeHead(401, { 'Content-Type': 'application/json' });
                                res.end(JSON.stringify({ success: false, message: '用户名或密码错误' }));
                                return;
                            }
                            
                            res.writeHead(200, { 'Content-Type': 'application/json' });
                            res.end(JSON.stringify({ success: true, uid: user.uid }));
                        } catch (error) {
                            res.writeHead(400, { 'Content-Type': 'application/json' });
                            res.end(JSON.stringify({ success: false, message: '无效请求' }));
                        }
                    });
                    return;
                }
                
                // 用户页面
                if (req.method === 'GET' && parsedUrl.pathname === '/user.html') {
                    res.writeHead(200, { 'Content-Type': 'text/html' });
                    res.end(fs.readFileSync(path.join(__dirname, 'user.html')));
                    return;
                }
                
                // 404处理
                res.writeHead(404);
                res.end('Not Found');
            });
            
            // 启动服务器
            const PORT = 3000;
            server.listen(PORT, () => {
                console.log(`服务器运行在 http://localhost:${PORT}`);
            });
        }
    </script>
</body>
</html>